package com.harvest.scientific.ladder.base

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.harvest.scientific.ladder.dialog.LoadingDialog
import com.harvest.scientific.ladder.page.AppModel
import com.harvest.scientific.ladder.util.FlowBus
import com.harvest.scientific.ladder.util.FlowBusConstant
import com.harvest.scientific.ladder.util.LocaleHelper
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.StbarUtil
import java.lang.reflect.ParameterizedType

open class BaNoActivity<VB : ViewBinding> : AppCompatActivity(), ILoading {

    protected val appModel by viewModels<AppModel>()
    protected var isFinished = false
    protected lateinit var _binding: VB
    protected var isRecreate = false

    companion object {
        const val IS_RECREATE = "is_recreate"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        LocaleHelper.setLocale(this, LocaleHelper.getPersistedData(this, "fr"))
        LogUtils.d("BaNoActivity onCreate")

        super.onCreate(savedInstanceState)
//        isRecreate = intent.getBooleanExtra(IS_RECREATE, true)
        if (isSetStatusbar()) {
            StbarUtil.setStatusBar(this, isDarkMode(), Color.TRANSPARENT, true)
        }
        createViewBinding()
        setContentView(_binding.root)
        initPage(savedInstanceState)

        FlowBus.with<Unit>(FlowBusConstant.UPDATE_LOCALE).register(this) {
            isRecreate = true
//            if (isRecreate) {
//                recreate()
//            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isRecreate) {
            recreate()
        }
    }

    protected open fun isDarkMode() = false

    protected open fun initPage(savedInstanceState: Bundle?) {

    }
    override fun attachBaseContext(newBase: Context?) {
        newBase ?: return super.attachBaseContext(newBase)
        val locale = LocaleHelper.getPersistedData(newBase, "fr")
        super.attachBaseContext(LocaleHelper.updateResources(newBase, locale))
    }

    fun switchLanguage(language: String) {
        LocaleHelper.setLocale(this, language)
        recreate()
    }

    //反射创建ViewBinding
    open protected fun createViewBinding() {

        val clazz: Class<*> =  (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>

        try {
            _binding = clazz.getMethod(
                "inflate", LayoutInflater::class.java
            ).invoke(null, layoutInflater) as VB

        } catch (e: Exception) {
            e.printStackTrace()
            throw IllegalArgumentException("无法通过反射创建ViewBinding对象")
        }

    }

    protected open fun isSetStatusbar(): Boolean {
        return false
    }

    private var loadingDialog: LoadingDialog? = null

    override fun showLoading() {
        loadingDialog ?: run {
            loadingDialog = LoadingDialog.Builder(this)
                .setIconType(LoadingDialog.Builder.ICON_TYPE_LOADING)
                .create()
        }

        loadingDialog?.show()

    }

    override fun dismissLoading() {
        loadingDialog?.dismiss()
    }

    override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
        handleFinish()
        return super.onOptionsItemSelected(menuItem)
    }

    open fun handleFinish() {
        supportFinishAfterTransition()
    }

    override fun onPause() {
        super.onPause()
        if (!isFinished && isFinishing) {
            isFinished = true
            onRecycler()
        }
    }

    override fun onDestroy() {
        if (!isFinished) {
            isFinished = true
            onRecycler()
        }
        super.onDestroy()
    }

    open fun onRecycler() {

    }

    protected fun addFragment(fragment: BaseFragment<*>, containerId: Int, tag: String? = ""): BaseFragment<*>? {
        return addFragment(fragment, containerId, false, tag)
    }

    protected fun addFragment(fragment: BaseFragment<*>, containerId: Int , needAddToBackStack: Boolean, tag: String? = ""): BaseFragment<*>? {
        val fm = supportFragmentManager
        val fragmentTransaction = fm.beginTransaction()
        if(tag.isNullOrEmpty()) {
            fragmentTransaction.replace(containerId, fragment)
        } else {
            fragmentTransaction.replace(containerId, fragment, tag)
        }
        if (needAddToBackStack) {
            fragmentTransaction.addToBackStack(null)
        }
        try {
            fragmentTransaction.commitAllowingStateLoss()
        } catch (e: Exception) {
        }
        return fragment
    }

}